package com.atbun.msmservice.controller;

import com.atbun.commonutils.R;
import com.atbun.msmservice.service.MsmService;
import com.atbun.msmservice.utils.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description : 手机短信发送方
 * @Author : mayp
 * @Date: 2020-05-15 08:28
 */
@RestController
@RequestMapping("/msmservice/sendmsm")
public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送手机短信验证码
     * @param phone
     * @return
     */
    @GetMapping("send/{phone}")
    public R phoneCode(@PathVariable String phone){
        String code = redisTemplate.opsForValue().get(phone);
//        如果redis中code存在没过期，就直接返回
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }
//        随机生成一个六位验证码
        code = RandomUtil.getSixBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
//        手机号码，自己的阿里云模板管理CODE，验证码类型（6位）
        boolean isSend = msmService.send(phone,"SMS_190266050",param);

        if (isSend){
//            如果发送成功，则把信息保存到redis，并设置过期时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else{
            return R.error().message("发送短信失败");
        }

    }
}
